{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "# Definition for a QuadTree node.\n",
    "class Node(object):\n",
    "    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n",
    "        self.val = val\n",
    "        self.isLeaf = isLeaf\n",
    "        self.topLeft = topLeft\n",
    "        self.topRight = topRight\n",
    "        self.bottomLeft = bottomLeft\n",
    "        self.bottomRight = bottomRight\n",
    "\"\"\"\n",
    "class Solution(object):\n",
    "    def construct(self, grid):\n",
    "        \"\"\"\n",
    "        :type grid: List[List[int]]\n",
    "        :rtype: Node\n",
    "        \"\"\"\n",
    "        if len(grid) == 0:\n",
    "            return None\n",
    "        \n",
    "        def constructTree(grid):\n",
    "            n = len(grid)\n",
    "            \n",
    "            if n == 1:\n",
    "                return Node(grid[0][0], True, None, None, None, None)\n",
    "            \n",
    "            \n",
    "            is_leaf = True\n",
    "            # Check if all elements of the grid are same\n",
    "            std = grid[0][0]\n",
    "            for l in grid:\n",
    "                if l.count(std) != n:\n",
    "                    is_leaf = False\n",
    "                    break\n",
    "\n",
    "            if is_leaf:\n",
    "                return Node(grid[0][0], True, None, None, None, None)\n",
    "            else:\n",
    "                node = Node('*', False, None, None, None, None)\n",
    "                mid = n // 2\n",
    "                node.topLeft = constructTree([x[0:mid] for x in grid[0:mid]])\n",
    "                node.topRight = constructTree([x[mid:] for x in grid[0:mid]])\n",
    "                node.bottomLeft = constructTree([x[0:mid] for x in grid[mid:]])\n",
    "                node.bottomRight = constructTree([x[mid:] for x in grid[mid:]])\n",
    "                \n",
    "                return node\n",
    "                                          \n",
    "        root = constructTree(grid)\n",
    "        \n",
    "        return root"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
